﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;

namespace EveryBookies.Common
{
    public static class JsonSerialization
    {
        /// <summary>
        /// Converts a dictionary into Json string
        /// </summary>
        /// <param name="dictionary"/>
        public static string s_ConvertToJson(this IDictionary<string, string> dictionary)
        {
            if (dictionary == null || dictionary.Count == 0)
            {
                return "{}";
            }

            var items = dictionary.Select(dict =>
            string.Format("\"{0}\":\"{1}\"", dict.Key, dict.Value));

            string json = "{" + string.Join(",", items) + "}";

            return json;
        }

        /// <summary>
        /// Serializes objects to the JavaScript Object Notation (JSON) string
        /// </summary>
        /// <typeparam name="T">Type param</typeparam>
        /// <param name="graph">Object to serialize</param>
        /// <returns></returns>
        public static string s_SerializeAsJson<T>(this T graph)
        {
            if (graph == null)
                return null;

            var ser = new DataContractJsonSerializer(typeof(T));
            var ms = new MemoryStream();
            ser.WriteObject(ms, graph);
            byte[] bytes = ms.ToArray();
            return Encoding.UTF8.GetString(bytes, 0, bytes.Length);
        }

        /// <summary>
        /// Deserializes JSON data to objects
        /// </summary>
        /// <typeparam name="T">Type param</typeparam>
        /// <param name="json">Data to deserialize</param>
        /// <returns>An instance of a type</returns>
        public static T s_Deserialize<T>(string json)
        {
            byte[] bytes = Encoding.Unicode.GetBytes(json);
            using (var stream = new MemoryStream(bytes))
            {
                var serializer = new DataContractJsonSerializer(typeof(T));
                return (T)serializer.ReadObject(stream);
            }
        }
    }
}